package web.study.tag;

import java.lang.reflect.Method;
import java.text.DecimalFormat;
import java.text.NumberFormat;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

public class MathTag extends TagSupport
{
    /**
     * 序列化
     */
    private static final long serialVersionUID = 1L;
    
    // 下面四个属性和math标签的四个属性相对应 
    private String method;
    
    private double value;
    
    private String pattern = "0.00";
    
    private boolean angle = false;
    
    public void setMethod(String method)
    {
        this.method = method;
    }
    
    public void setValue(double value)
    {
        this.value = value;
    }
    
    public void setangle(boolean angle)
    {
        this.angle = angle;
    }
    
    public void setPattern(String pattern)
    {
        this.pattern = pattern;
    }
    
    public int doStartTag()
        throws JspException
    {
        try
        {
            // 获得指定静态方法的Method对象 
            Method m = Math.class.getMethod(method, new Class[] {double.class});
            NumberFormat nf = NumberFormat.getNumberInstance();
            DecimalFormat df = (DecimalFormat)nf;
            
            // 应用模式字符串 
            df.applyPattern(pattern);
            
            // 如果angle属性值为true（value属性值表示角度），将value属性值转换成弧度 
            if (angle)
            {
                value = Math.toRadians(value);
            }
            
            // 动态调用Math类指定的静态方法，并格式化返回值 
            String result = df.format(m.invoke(null, value));
            
            // 将格式化后的结果输出的客户端 
            pageContext.getOut().println(result);
            
        }
        catch (Exception e)
        {
            throw new JspException(e.getMessage());
        }
        return super.doStartTag();
    }
}
